import React, { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, Database, Loader2, AlertCircle } from 'lucide-react'

interface PartitionInfo {
  partition: number
  leader: number
  replicas: number[]
  isr: number[]
  messageCount?: number
  latestOffset?: number
}

interface CompactPartitionSelectorProps {
  partitions: number[]
  partitionDetails: PartitionInfo[]
  selectedPartition?: number
  onPartitionChange: (partition: number | undefined) => void
  loading: boolean
  error: string | null
  topicName?: string
}

export default function CompactPartitionSelector({
  partitions,
  partitionDetails,
  selectedPartition,
  onPartitionChange,
  loading,
  error,
  topicName
}: CompactPartitionSelectorProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 })
  const buttonRef = useRef<HTMLButtonElement>(null)

  // 当组件卸载或props变化时，确保关闭下拉菜单
  useEffect(() => {
    setIsOpen(false)
  }, [topicName, partitions])

  // 计算下拉菜单位置
  const updateDropdownPosition = () => {
    if (buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect()
      setDropdownPosition({
        top: rect.bottom + window.scrollY + 4,
        left: rect.left + window.scrollX,
        width: rect.width
      })
    }
  }



  const getPartitionDetail = (partitionNum: number) => {
    return partitionDetails.find(p => p.partition === partitionNum)
  }

  const formatNumber = (num?: number) => {
    if (num === undefined || num === null) return '-'
    return num.toLocaleString()
  }

  const getSelectedText = () => {
    if (selectedPartition === undefined) {
      return '所有分区'
    }
    return `分区 ${selectedPartition}`
  }

  const getStatusText = () => {
    if (loading) return '加载中...'
    if (error) return '加载失败'
    if (partitions.length === 0) return '无分区'
    return `${partitions.length} 个分区`
  }

  return (
    <div className="relative">
      {/* 分区选择器按钮 */}
      <button
        ref={buttonRef}
        onClick={() => {
          if (!isOpen) {
            updateDropdownPosition()
          }
          setIsOpen(!isOpen)
        }}
        className="w-full flex items-center justify-between p-3 bg-white border border-gray-300 rounded-lg hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-colors"
      >
        <div className="flex items-center space-x-2">
          <Database className="w-4 h-4 text-gray-500" />
          <div className="text-left">
            <div className="text-sm font-medium text-gray-900">
              {getSelectedText()}
            </div>
            <div className="text-xs text-gray-500 flex items-center space-x-1">
              {loading && <Loader2 className="w-3 h-3 animate-spin" />}
              {error && <AlertCircle className="w-3 h-3 text-red-500" />}
              <span>{getStatusText()}</span>
            </div>
          </div>
        </div>
        <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {/* 使用Portal渲染下拉菜单到body，避免被父容器截断 */}
      {isOpen && createPortal(
        <>
          {/* 遮罩层 - 只在下拉菜单打开时显示 */}
          <div
            className="fixed inset-0 z-40"
            onClick={() => setIsOpen(false)}
          />

          {/* 下拉内容 */}
          <div
            className="absolute z-50 bg-white border border-gray-200 rounded-lg shadow-lg max-h-64 overflow-y-auto"
            style={{
              top: dropdownPosition.top,
              left: dropdownPosition.left,
              width: dropdownPosition.width,
              minWidth: '200px'
            }}
          >
            {/* 所有分区选项 */}
            <button
              onClick={() => {
                onPartitionChange(undefined)
                setIsOpen(false)
              }}
              className={`w-full p-3 text-left hover:bg-gray-50 border-b border-gray-100 ${
                selectedPartition === undefined ? 'bg-primary-50 text-primary-700' : 'text-gray-700'
              }`}
            >
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-medium">所有分区</div>
                  <div className="text-xs text-gray-500">消费所有分区的消息</div>
                </div>
                {selectedPartition === undefined && (
                  <div className="w-2 h-2 bg-primary-500 rounded-full"></div>
                )}
              </div>
            </button>

            {/* 错误提示 */}
            {error && (
              <div className="p-3 bg-red-50 border-b border-gray-100">
                <div className="flex items-center space-x-2 text-red-600">
                  <AlertCircle className="w-4 h-4" />
                  <span className="text-xs">{error}</span>
                </div>
              </div>
            )}

            {/* 分区列表 */}
            {partitions.length > 0 ? (
              partitions.map((partitionNum) => {
                const detail = getPartitionDetail(partitionNum)
                const isSelected = selectedPartition === partitionNum
                const hasDetail = detail !== undefined
                
                return (
                  <button
                    key={partitionNum}
                    onClick={() => {
                      onPartitionChange(partitionNum)
                      setIsOpen(false)
                    }}
                    className={`w-full p-3 text-left hover:bg-gray-50 ${
                      isSelected ? 'bg-primary-50 text-primary-700' : 'text-gray-700'
                    } ${partitionNum === partitions[partitions.length - 1] ? '' : 'border-b border-gray-100'}`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex-1">
                        <div className="flex items-center space-x-2">
                          <span className="font-medium">分区 {partitionNum}</span>
                          {hasDetail && (
                            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                          )}
                          {isSelected && (
                            <div className="w-2 h-2 bg-primary-500 rounded-full"></div>
                          )}
                        </div>
                        
                        {hasDetail ? (
                          <div className="text-xs text-gray-500 mt-1 space-y-0.5">
                            <div>Leader: {detail.leader} | 副本: {detail.replicas.length}</div>
                            {detail.messageCount !== undefined && (
                              <div>消息数: {formatNumber(detail.messageCount)}</div>
                            )}
                          </div>
                        ) : loading ? (
                          <div className="flex items-center space-x-1 text-xs text-gray-500 mt-1">
                            <Loader2 className="w-3 h-3 animate-spin" />
                            <span>加载详情...</span>
                          </div>
                        ) : (
                          <div className="text-xs text-gray-500 mt-1">
                            点击查看详情
                          </div>
                        )}
                      </div>
                    </div>
                  </button>
                )
              })
            ) : !loading && !error && (
              <div className="p-6 text-center text-gray-500">
                <Database className="w-8 h-8 mx-auto mb-2 text-gray-300" />
                <div className="text-sm">
                  {topicName ? `Topic "${topicName}" 暂无分区信息` : '请先选择一个Topic'}
                </div>
              </div>
            )}

            {/* 加载占位符 */}
            {loading && partitions.length === 0 && (
              <div className="p-3">
                {[...Array(3)].map((_, index) => (
                  <div
                    key={index}
                    className={`p-2 animate-pulse ${index < 2 ? 'border-b border-gray-100' : ''}`}
                  >
                    <div className="h-4 bg-gray-300 rounded w-20 mb-1"></div>
                    <div className="h-3 bg-gray-300 rounded w-32"></div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </>,
        document.body
      )}
    </div>
  )
}
